from utils import log_error
from dao.practice_progress_dao import PracticeProgressDAO
from datetime import datetime, timedelta

class HomeService:
    """首页服务类，处理首页相关的业务逻辑"""

    def __init__(self):
        """初始化HomeService

        Args:
            db_path: 数据库文件路径
        """

        self.practice_progress_dao = PracticeProgressDAO()

    def save_practice_progress(self, category, index, user_id):
        """保存练习进度

        Args:
            category: 题目类别(A/B/C)
            index: 当前练习索引
            user_id: 用户ID
        """
        try:
            # 检查是否已存在该用户的练习进度
            existing_progress = self.practice_progress_dao.get_by_user_and_category(user_id, category)

            if existing_progress:
                # 更新现有进度
                existing_progress.progress = index
                return self.practice_progress_dao.update(existing_progress)
            else:
                # 创建新进度记录
                from models.practice_progress import PracticeProgress
                new_progress = PracticeProgress(
                    user_id=user_id,
                    category=category,
                    progress=index
                )
                return self.practice_progress_dao.create(new_progress)
        except Exception as e:
            log_error(f"保存练习进度时发生错误: {e}")
            return False

    def format_last_login(self, last_login_str):
        """格式化上次登录时间

        Args:
            last_login_str: 上次登录时间字符串
        """
        try:
            # 将字符串转换为datetime对象
            last_login = datetime.strptime(last_login_str, '%Y-%m-%d %H:%M:%S')
            # 直接返回格式化的时间字符串（无需时区转换，因为数据库中存储的已经是本地时间）
            return last_login.strftime('%Y-%m-%d %H:%M:%S')
        except Exception as e:
            log_error(f"格式化上次登录时间时发生错误: {e}")
            return last_login_str